<template>
  <div class="device-container">
    <el-form
      v-loading="deviceFormLoading"
      :ref="deviceFormRef"
      :model="deviceForm"
      :rules="deviceFormRules"
      size="small" label-width="120px">
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="设备类型" prop="deviceTypeId">
            <el-select
              v-model="deviceForm.deviceTypeId"
              clearable filterable
              class="width-100"
              placeholder="请选择设备类型"
              @change="deviceTypeChange">
              <el-option
                v-for="(deviceType, idx) in deviceTypeList" :key="idx"
                :label="deviceType.name" :value="deviceType._id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备厂家" prop="manufacturerId">
            <el-select
              v-model="deviceForm.manufacturerId"
              clearable filterable
              class="width-100"
              placeholder="请选择设备厂家"
              @change="manufacturerChange">
              <el-option
                v-for="(manufacturer, idx) in manufacturerList" :key="idx"
                :label="manufacturer.label" :value="manufacturer.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备系列">
            <el-select
              v-model="deviceForm.seriesId"
              clearable filterable
              class="width-100"
              placeholder="请选择设备系列"
              @change="seriesChange">
              <el-option
                v-for="(series, idx) in seriesList" :key="idx"
                :label="series.label" :value="series.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备型号">
            <el-select
              v-model="deviceForm.deviceId"
              clearable filterable
              class="width-100"
              placeholder="请选择设备型号"
              @change="deviceChange">
              <el-option
                v-for="(device, idx) in deviceList" :key="idx"
                :label="device.deviceName" :value="device._id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="显示特定协议" prop="showMark">
            <el-switch
              v-model="deviceForm.showMark"
              @change="getDeviceData"
            >
            </el-switch>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!--所有设备列表-->
    <div>
      <div class="device-title">所有设备</div>
      <el-table :data="allDeviceList" border size="mini" class="mar-btm" height="200px">
        <el-table-column label="设备编码" prop="deviceCode" width="100"></el-table-column>
        <el-table-column label="设备类别" prop="deviceTypeName" width="150" show-overflow-tooltip></el-table-column>
        <el-table-column label="厂家" prop="manufacturerName" show-overflow-tooltip></el-table-column>
        <el-table-column label="系列" prop="seriesName" show-overflow-tooltip></el-table-column>
        <el-table-column label="型号" prop="modelName" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" width="160">
          <template slot-scope="scope">
            <el-popover
              placement="top"
              ref="popoverRef"
              width="300"
              trigger="click">
              <div v-for="(item,index) in scope.row.protocols" :key="index" class="hover-row mar-btm-5"
                   @click="selectProtocol(scope.row,item.protocol)">{{index + 1}}.{{item.protocolName}}
              </div>
              <el-button size="small" slot="reference">选择</el-button>
            </el-popover>

          </template>
        </el-table-column>
      </el-table>
    </div>
    <!--已选设备列表-->
    <div v-show="selectDeviceList.length>0">
      <div class="device-title">已选设备</div>
      <el-table :data="selectDeviceList" border size="mini" class="mar-btm" height="200px">
        <el-table-column label="设备编码" prop="deviceCode" width="100"></el-table-column>
        <el-table-column label="设备类别" prop="deviceTypeName" width="150" show-overflow-tooltip></el-table-column>
        <el-table-column label="厂家" prop="manufacturerName" show-overflow-tooltip></el-table-column>
        <el-table-column label="系列" prop="seriesName" show-overflow-tooltip></el-table-column>
        <el-table-column label="型号" prop="modelName" show-overflow-tooltip></el-table-column>
        <el-table-column label="协议" show-overflow-tooltip>
          <template slot-scope="scope">
            {{scope.row.protocols[0].protocolName}}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160">
          <template slot-scope="scope">
            <el-button size="small" type="danger" @click="removeList(scope.$index)">移除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>
<script>
  import API from "@/api";
  import _ from "lodash";
  import {messageHandle} from "@/utils";

  export default {
    name: "ChoseDevice",
    data() {
      return {
        deviceFormLoading: false,
        deviceFormRef: 'deviceFormRef',
        deviceForm: {
          deviceTypeId: '',
          manufacturerId: '',
          seriesId: '',
          deviceId: '',
          showMark: false
        },
        deviceFormRules: {
          deviceTypeId: [
            {required: true, message: '请选择设备类型', trigger: 'change'}
          ],
          manufacturerId: [
            {required: true, message: '请选择设备厂家', trigger: 'change'}
          ],
        },
        manufacturerList: [],
        seriesList: [],
        deviceList: [],
        protocolList: [],
        deviceTypeList: [],
        tableLoading: false,
        allDeviceList: [],//所有设备
        selectDeviceList: [],//已选设备
        //请求设备集合接口的值
        deviceType: '',
        manufacturer: '',
        series: '',
        model: '',
      }
    },
    mounted() {
      this.getDeviceTypeList();
    },
    methods: {
      initForm() {
        console.log('initForm');
        this.deviceType = ''
        this.manufacturer = ''
        this.series = ''
        this.model = ''
        this.deviceForm.deviceTypeId = ''
        this.deviceForm.manufacturerId = ''
        this.deviceForm.seriesId = ''
        this.deviceForm.deviceId = ''
        this.allDeviceList = []
        this.selectDeviceList = []

        const deviceForm = this.$refs[this.deviceFormRef];
        deviceForm && deviceForm.resetFields();
      },
      getDeviceTypeList() {
        API.deviceType.deviceTypeAll().then(resp => {
          const {data = []} = resp;
          this.deviceTypeList = data;
        }).catch(err => {
          console.log('err', err);
        });
      },
      deviceTypeChange(val) {
        this.deviceForm.seriesId = '';
        this.deviceForm.modelId = '';
        this.deviceForm.deviceId = '';
        this.deviceForm.protocolId = '';
        this.deviceForm.manufacturerId = '';
        this.seriesList = [];
        this.deviceList = [];
        this.protocolList = [];
        this.getManufacturerList();
        this.deviceType = val;
        this.manufacturer = '';
        this.series = '';
        this.model = '';
      },
      getManufacturerList() {
        const param = {
          deviceType: this.deviceForm.deviceTypeId
        };
        API.manufacturer.manufacturerByDeviceType(param).then(resp => {
          const {data = []} = resp;
          this.manufacturerList = data;
        }).catch(err => {
          console.log('err', err);
        });
      },
      manufacturerChange(val) {
        this.deviceForm.seriesId = '';
        this.deviceForm.modelId = '';
        this.deviceForm.deviceId = '';
        this.deviceForm.protocolId = '';
        this.seriesList = [];
        this.deviceList = [];
        this.protocolList = [];
        this.getSeriesList();
        this.manufacturer = val;
        this.series = '';
        this.model = '';
        this.getDeviceData();
      },
      getSeriesList() {
        const param = {
          deviceType: this.deviceForm.deviceTypeId,
          manufacturer: this.deviceForm.manufacturerId
        };
        API.series.seriesByManufacturer(param).then(resp => {
          const {data = []} = resp;
          this.seriesList = data;
        }).catch(err => {
          console.log('err', err);
        });
      },
      seriesChange(val) {
        this.deviceForm.modelId = '';
        this.deviceForm.deviceId = '';
        this.deviceForm.protocolId = '';
        this.deviceList = [];
        this.protocolList = [];
        this.getDeviceList();
        this.series = val;
        this.model = '';
        this.getDeviceData();
      },
      getDeviceList() {
        const param = {
          deviceType: this.deviceForm.deviceTypeId,
          manufacturer: this.deviceForm.manufacturerId,
          series: this.deviceForm.seriesId
        };
        API.device.deviceAll(param).then(resp => {
          const {data = []} = resp;
          this.deviceList = data;
        }).catch(err => {
          console.log('err', err);
        });
      },
      deviceChange(deviceId) {
        const device = this.deviceList.find(d => d._id === deviceId);
        const {model = '', protocols = []} = device;
        this.deviceForm.modelId = model;
        this.deviceForm.protocolId = '';
        this.deviceForm.protocols = _.map(protocols, 'protocol');
        this.protocolList = [];
        this.model = model;
        this.getDeviceData();
      },

      getDeviceData() {
        this.tableLoading = true;
        const selector = {
          ...(this.deviceType && {deviceType: this.deviceType}),
          ...(this.manufacturer && {manufacturer: this.manufacturer}),
          ...(this.series && {series: this.series}),
          ...(this.model && {model: this.model}),
        };
        const filters=[{key:'protocolMark',fieldType:'string','value':this.deviceForm.showMark?[1,2]:[1]}]

        const tableParam = {
          pageNo: 1,
          pageSize: 100,
        }
        API.device.deviceList({selector, filters,...tableParam}).then(result => {
          this.tableLoading = false;
          const {data = []} = result;
          this.allDeviceList = data;

        }).catch(err => {
          console.log('err', err)
          this.tableLoading = false;
        });
      },
      //选择设备协议
      selectProtocol(device, protocolId) {
        const protocols = device.protocols.filter(p => p.protocol === protocolId);
        const newDevice = _.cloneDeep(device);
        newDevice.protocols = protocols;
        newDevice.protocolId = protocolId;
        // const item = this.selectDeviceList.find(d => d.protocolId === protocolId)
        // if (item !== undefined) {
        //   this.$message({
        //     message: '该协议已存在',
        //     type: 'warning'
        //   });
        // } else {
        //   this.selectDeviceList.push(newDevice);
        // }
        this.selectDeviceList.push(newDevice);
        this.$emit('selectDevice', this.selectDeviceList);
        this.$refs.popoverRef.doClose()
      },
      //移除已选设备
      removeList(idx) {
        this.selectDeviceList.splice(idx, 1);
        this.$emit('selectDevice', this.selectDeviceList);
      }
    }
  }
</script>
<style scoped lang="less">
  .device-container {
    width: 100%;

    .device-title {
      border-left: 4px solid #e0572d;
      margin: 5px 0;
      padding: 0 5px;
      font-weight: bold;

    }
  }

  .hover-row:hover {
    color: #2D69E0;
    cursor: pointer;
  }
</style>
